package com.thingple.usb.manager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.util.Log;

import org.jetbrains.annotations.NotNull;

public abstract class AbstractUsbReceiver extends BroadcastReceiver implements UsbDeviceManager {
    private static final String TAG = AbstractUsbReceiver.class.getName();

    private final UsbDeviceFilter filter = new UsbDeviceFilter();

    public boolean filterEnable = false;

    protected UsbManager usbManager;

    @Override
    public void registerSpec(String vendorId, String productId) {
        filterEnable = true;
        filter.registerSpec(vendorId, productId);
    }
    @Override
    public void registerSpec(String vendor) {
        registerSpec(vendor, "*");
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action == null) {
            return;
        }
        UsbAccessory device;
        switch (action) {
            case UsbManager.ACTION_USB_DEVICE_ATTACHED:
                device = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
                if (device == null) {
                    return;
                }
                handleDeviceAttach(device);
                break;
            case UsbManager.ACTION_USB_DEVICE_DETACHED:
                device = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
                if (device == null) {
                    return;
                }
                Log.d(TAG, "usb detached");
                onDeviceDetached(device);
                break;
            default:
                onUnknownAction(context, intent);
        }
    }

    protected void handleDeviceAttach(UsbAccessory device) {
        if (device == null) {
            return;
        }
        Log.d(TAG, "usb attached");
        if (filterEnable && !filter.check(device)) {
            return;
        }
        onDeviceAttached(device);
    }

    protected void onUnknownAction(Context context, Intent intent) {

    }

    protected void onDeviceAttached(@NotNull UsbAccessory device) {

    }
    protected void onDeviceDetached(@NotNull UsbAccessory device) {

    }
}
